﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

//퍼포스 테스트

public class Lobby20vs : Scene
{
    const short MaxFormationMember = 20;
    const short SkillNum = 5;
    enum SCENEMODE
    {
        ready,
        change
    }

    bool m_IsInit = false;

    SCENEMODE m_SceneMode = SCENEMODE.ready;

    MemberModel m_SelectMember = null;

    #region Left List 관련 변수
    int m_MembersMax = 0;
    List<int> m_MembersNo = new List<int>();
    public UIScrollView m_MemberScroll;
    public GameObject m_LeftListOrizin;
    const float ListMemberStartY = 300.0f;
    const float ListMemberGap = 195.0f;
    List<Oc_MemberListItem_2> m_LeftListItems = new List<Oc_MemberListItem_2>();

    #endregion

    public Animation m_ModeChangeAni;
    public Animation m_SortAni;
    public Animation m_SortAni_Kind;

    bool m_IsDescending = true;

    #region 길드원 정렬 관련 변수

    public UILabel[] m_SortKindsLabel;
    public UILabel[] m_KindSortKindsLabel;

    bool m_IsSortMenuOn = false;
    bool IsSortMenuOn
    {
        get { return m_IsSortMenuOn; }
        set
        {
            m_IsSortMenuOn = value;
            MemberListScrollOnOff();
        }
    }
    bool m_IsKindSortMenuOn = false;

    int m_FormationKind = 0;

    FormationSortKind m_SortKind = FormationSortKind.Level;

    const int SortingNum = 13;
    string[] tempString = new string[SortingNum]
    {
        "uiCommonTextLevel", 
        "uiCommonTextEnhance",
        "combatStat20",
        "combatAtkType1",
        "combatAtkType2",
        "combatAtkType3",
        "combatAtkType4",
        "combatAtkType5",
        "combatDefType1",
        "combatDefType2",
        "combatDefType3",
        "combatDefType4",
        "combatDefType5"
    };

    const int FormationMax = 3;

    #endregion

    public Transform m_Formation;
    Oc_FormationItem[] m_FormationList = null;

    public GameObject m_SelectFx1;
    public GameObject m_SelectFx2;


    #region 그래프 관련 변수

    public Transform m_GraphRoot_Att;
    public Transform m_GraphRoot_Def;

    UISlider[] m_Graph_Att_On = new UISlider[SkillNum];
    UISlider[] m_Graph_Def_On = new UISlider[SkillNum];

    UISlider[] m_Graph_Att_Off = new UISlider[SkillNum];
    UISlider[] m_Graph_Def_Off = new UISlider[SkillNum];

    UILabel[] m_Graph_Att_Value = new UILabel[SkillNum];
    UILabel[] m_Graph_Def_Value = new UILabel[SkillNum];
    #endregion

    public List<int> m_MemberBattleArray = new List<int>();

    public UILabel m_InfoOfFormaion;
    public GameObject m_Noti_NonFormaion;

    int m_FormationMemberNum = 0;

    public Transform m_3DModelRoot;
    Transform[] m_3DModelPosition = new Transform[Constants.FormationNum];
    public Transform m_3DModelColorPosRoot;
    //Material[] m_ColorPos = new Material[Constants.FormationNum];

    #region 메뉴 컨트롤 부분

    bool m_IsCanBattle = false; //포메이션이 비어있지않을때 배틀 가능

    void SetSortMenuUI(int num)        // 소트 메뉴 라벨 설정
    {
        SetSortMenuUI((FormationSortKind)num);
    }


    void SetSortMenuUI(FormationSortKind kind)        // 소트 메뉴 라벨 설정
    {
        m_SortKind = kind;   // 각 상황마다 대응
        SortMember();
        SetLeftListUI();
        RefreshFormationData();

        m_SortKindsLabel[0].text = TextController.GetStringWithId(tempString[(int)m_SortKind]);

        // 소팅 종류에 따라 값 변경
        foreach (Oc_FormationItem tFI in m_FormationList)
        {
            tFI.SetSubjectAndValue(m_SortKind);
        }

        if (m_SelectMember != null)
        {
            for (int i = 0; i < m_LeftListItems.Count; i++)
            {
                if (m_SelectMember.no == m_LeftListItems[i].m_MemberModel.no)
                {
                    m_LeftListItems[i].SetOn(false);
                    SetLeftListPos(m_LeftListItems[i]);
                }
                else
                    m_LeftListItems[i].SetOff();
            }
        }
    }

    void SetKindSortMenuUI(int num)        // 소트 메뉴 라벨 설정
    {
        m_FormationKind = num;

        m_KindSortKindsLabel[0].text = string.Format(TextController.GetStringWithId("forceFormationCombobox"), num + 1);      

        SortMember();
        SetLeftListUI();

        if (m_SceneMode == SCENEMODE.change)
        {
            SaveFormation();
            SetFormation(false);
        }
        else
        {
            RefreshFormationData();
        }
    }

    void SortMember()
    {
        m_MembersNo.Clear();

        List<MemberModel> tList = new List<MemberModel>();

        if (m_SceneMode == SCENEMODE.ready)
        {
            for (int i = 0; i < Constants.FormationNum; i++)
            {
                int t = UserData.Instance.userModel.memberBattleArray[i + (m_FormationKind * Constants.FormationNum)];

                if (t != 0)
                {
                    if (UserData.Instance.userModel.members_dic.ContainsKey(t.ToString()))
                        tList.Add(UserData.Instance.userModel.members_dic[t.ToString()]);
                }
            }
        }
        else if (m_SceneMode == SCENEMODE.change)
        {
            foreach (KeyValuePair<string, MemberModel> t in UserData.Instance.userModel.members_dic)
            {
                tList.Add(t.Value);
            }
        }

        int max = tList.Count;
        for (int i = 0; i < max - 1; i++)
        {
            for (int j = 0; j < max - 1; j++)
            {
                switch (m_SortKind)
                {
                    case FormationSortKind.Level:
                        {
                            if (tList[j].level < tList[j + 1].level)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Inhance:
                        {
                            if (tList[j].strengthening < tList[j + 1].strengthening)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.HP:
                        {
                            if (tList[j].m_Stat.data.baseHP < tList[j + 1].m_Stat.data.baseHP)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Near_Att:
                        {
                            int a = 0; int b = 0;

                            if (tList[j].m_Stat.data.atkType == 1)
                                a = tList[j].m_Stat.data.baseAtk;

                            if (tList[j + 1].m_Stat.data.atkType == 1)
                                b = tList[j].m_Stat.data.baseAtk;

                            if (a < b)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Far_Att:
                        {
                            int a = 0; int b = 0;

                            if (tList[j].m_Stat.data.atkType == 2)
                                a = tList[j].m_Stat.data.baseAtk;

                            if (tList[j + 1].m_Stat.data.atkType == 2)
                                b = tList[j].m_Stat.data.baseAtk;

                            if (a < b)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Magic_Att:
                        {
                            int a = 0; int b = 0;

                            if (tList[j].m_Stat.data.atkType == 3)
                                a = tList[j].m_Stat.data.baseAtk;

                            if (tList[j + 1].m_Stat.data.atkType == 3)
                                b = tList[j].m_Stat.data.baseAtk;

                            if (a < b)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Wave_Att:
                        {
                            int a = 0; int b = 0;

                            if (tList[j].m_Stat.data.atkType == 4)
                                a = tList[j].m_Stat.data.baseAtk;

                            if (tList[j + 1].m_Stat.data.atkType == 4)
                                b = tList[j].m_Stat.data.baseAtk;

                            if (a < b)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Special_Att:
                        {
                            int a = 0; int b = 0;

                            if (tList[j].m_Stat.data.atkType == 5)
                                a = tList[j].m_Stat.data.baseAtk;

                            if (tList[j + 1].m_Stat.data.atkType == 5)
                                b = tList[j].m_Stat.data.baseAtk;

                            if (a < b)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Near_Def:
                        {
                            if (tList[j].m_Stat.data.melee < tList[j + 1].m_Stat.data.melee)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Far_Def:
                        {
                            if (tList[j].m_Stat.data.range < tList[j + 1].m_Stat.data.range)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Magic_Def:
                        {
                            if (tList[j].m_Stat.data.magic < tList[j + 1].m_Stat.data.magic)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Wave_Def:
                        {
                            if (tList[j].m_Stat.data.pulse < tList[j + 1].m_Stat.data.pulse)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case FormationSortKind.Special_Def:
                        {
                            if (tList[j].m_Stat.data.special < tList[j + 1].m_Stat.data.special)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                }
            }
        }

        for (int i = 0; i < max; i++)
        {
            if (m_IsDescending)
                m_MembersNo.Add(tList[i].no);
            else
                m_MembersNo.Add(tList[max - i - 1].no);
        }
    }

    void OnLoginErrCallback(ResponseModel<UserModel> recvData)
    {
        Debug.LogError("OnLoginErrCallback");
    }

    void OnLoginCallback(ResponseModel<UserModel> userData)
    {
        UserData.Instance.userModel = userData.data;
        StartCoroutine("StartSceneWithDelay");
    }

    bool isTestLoginVer = false;
    public override void AwakeScene()
    {
        Instance = this;

        Transform tempTr = null;
        for (int i = 0; i < SkillNum; i++)
        {
            tempTr = m_GraphRoot_Att.FindChild(string.Format("graph{0}", i + 1));
            m_Graph_Att_On[i] = tempTr.FindChild("on").GetComponent("UISlider") as UISlider;
            m_Graph_Att_Value[i] = m_Graph_Att_On[i].transform.FindChild("Text_Num").GetComponent("UILabel") as UILabel;
            m_Graph_Att_Off[i] = tempTr.FindChild("off").GetComponent("UISlider") as UISlider;

            tempTr = m_GraphRoot_Def.FindChild(string.Format("graph{0}", i + 1));
            m_Graph_Def_On[i] = tempTr.FindChild("on").GetComponent("UISlider") as UISlider;
            m_Graph_Def_Value[i] = m_Graph_Def_On[i].transform.FindChild("Text_Num").GetComponent("UILabel") as UILabel;
            m_Graph_Def_Off[i] = tempTr.FindChild("off").GetComponent("UISlider") as UISlider;
        }

        if (m_FormationList == null)
        {
            m_FormationList = new Oc_FormationItem[Constants.FormationNum];

            for (int i = 0; i < m_FormationList.Length; i++)
            {
                m_FormationList[i] = m_Formation.FindChild(string.Format("Cell_Formation_{0}", i)).GetComponent("Oc_FormationItem") as Oc_FormationItem;
                m_FormationList[i].index = i;
            }
        }


        for (int i = 0; i < SortingNum; i++)
        {
            m_SortKindsLabel[i].text =  TextController.GetStringWithId(tempString[i]);
        }


        for (int i = 0; i < FormationMax; i++)
        {
            m_KindSortKindsLabel[i].text = string.Format(TextController.GetStringWithId("forceFormationCombobox"), i + 1);  
        }


        // test version code  /////////////////////////////////////////////
        /**/
        if (UserData.Instance.userModel == null)
        {
            isTestLoginVer = true;

            LoadingScene.TestInit();
            /**/
            //NetworkManager.Instance.C2S_LOGIN(AuthPlatformID.None, "hshshs", string.Empty, OnLoginCallback, OnLoginErrCallback);
            NetworkManager.Instance.C2S_GSTAR_JOIN(OnLoginCallback, OnLoginErrCallback);


        }
    }


    public override void StartScene()
    {
        if (!isTestLoginVer)
        {
            StartCoroutine("StartSceneWithDelay");
        }
    }


    IEnumerator StartSceneWithDelay()
    {
        yield return new WaitForSeconds(0.0f);

        m_MembersMax = UserData.Instance.userModel.members_dic.Count;

        CreateList();
        GoReadyMode();
        SetFormation(true);
    }

    void CreateList()
    {
        SortMember();

        // 레프트 메뉴 x -700 에서 씬 시작
        GameObject temp = null;
        Oc_MemberListItem_2 tempML = null;

        Vector3 pos = Vector3.zero;

        for (int i = 0; i < m_MembersMax; i++)
        {
            if (i > 0)
                temp = Instantiate(m_LeftListOrizin) as GameObject;
            else
                temp = m_LeftListOrizin;

            temp.transform.parent = m_LeftListOrizin.transform.parent;
            temp.transform.localScale = m_LeftListOrizin.transform.localScale;

            pos = temp.transform.localPosition;
            pos.x = -30.0f;
            pos.y = ListMemberStartY - (ListMemberGap * i);
            temp.transform.localPosition = pos;

            temp.name = string.Format("memberList_A{0}", i + 1);
            tempML = temp.GetComponent("Oc_MemberListItem_2") as Oc_MemberListItem_2;
            m_LeftListItems.Add(tempML);
        }

        for (int i = 0; i < m_3DModelPosition.Length; i++)
        {
            m_3DModelPosition[i] = m_3DModelRoot.Find(string.Format("{0:00}", i + 1));
            //m_ColorPos[i] = m_3DModelColorPosRoot.Find(string.Format("Hexagon_Board_{0:00}", i + 1)).renderer.material;
        }
    }


    void SetLeftListPos(Oc_MemberListItem_2 item)
    {       
        Vector3 pos = Vector3.zero;
        float OnListGap = 0.0f;
        for (int i = 0; i < m_MembersMax; i++)
        {
            if (m_LeftListItems[i].gameObject.activeSelf)   // 사용 하는 아이템만 포지션 변경
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = -30.0f;
                pos.y = ListMemberStartY - (ListMemberGap * i) - OnListGap;
                m_LeftListItems[i].transform.localPosition = pos;

                if (item == m_LeftListItems[i])
                {
                    Debug.Log("asdfasdf");
                    OnListGap = 20.0f;
                }
            }
        }
    }



    void SetLeftListUI()
    {
        //진형수정을 눌러주세요 유무
        m_Noti_NonFormaion.SetActive(m_MembersNo.Count == 0);

        if (m_SceneMode == SCENEMODE.ready)
        {
            for (int i = 0; i < m_LeftListItems.Count; i++)
            {
                if (i < m_MembersNo.Count)
                {
                    m_LeftListItems[i].SetList(UserData.Instance.userModel.members_dic[m_MembersNo[i].ToString()]);
                    m_LeftListItems[i].SetListWithSortingKind(m_SortKind);
                    m_LeftListItems[i].gameObject.SetActive(true);
                    m_LeftListItems[i].SetOff();
                    m_LeftListItems[i].SetSelect(false);
                }
                else
                    m_LeftListItems[i].gameObject.SetActive(false);
            }
        }
        else if (m_SceneMode == SCENEMODE.change)      //여기 수정
        {
            for (int i = 0; i < m_LeftListItems.Count; i++)
            {
                m_LeftListItems[i].SetList(UserData.Instance.userModel.members_dic[m_MembersNo[i].ToString()]);
                m_LeftListItems[i].SetListWithSortingKind(m_SortKind);
                m_LeftListItems[i].gameObject.SetActive(true);
                m_LeftListItems[i].SetOff();
            }

            //if (m_MembersNo.Count > 0)  // 첫번째 멤버 선택
            if (m_SelectMember != null)
            {
                //m_SelectMember = m_LeftListItems[0].m_MemberModel;
                //m_LeftListItems[0].SetOn(false);

                foreach (Oc_FormationItem tFi in m_FormationList)
                {
                    if (tFi.m_Member != null)
                    {
                        tFi.SetOnOff(tFi.m_Member.no == m_SelectMember.no);
                    }
                }
            }
        }
    }


    void ResetScrollView()
    {
        Vector3 pos = m_MemberScroll.transform.localPosition;
        pos.y = -2;
        m_MemberScroll.transform.localPosition = pos;

        UIPanel pn = m_MemberScroll.GetComponent("UIPanel") as UIPanel;
        pn.clipOffset = new Vector2(0, -30);
    }

    void MemberListScrollOnOff()
    {
        foreach(Oc_MemberListItem_2 item in m_LeftListItems)
        {
            UIDragScrollView sv = item.GetComp("UIDragScrollView") as UIDragScrollView;
            sv.enabled = !IsSortMenuOn;
        }
    }

    void MoveScrollView(int index)
    {
        if (index < m_LeftListItems.Count - 4)
        {
            Vector3 pos = m_MemberScroll.transform.localPosition;
            pos.y = -2 + (index * ListMemberGap);
            m_MemberScroll.transform.localPosition = pos;

            UIPanel pn = m_MemberScroll.GetComponent("UIPanel") as UIPanel;
            pn.clipOffset = new Vector2(0, -30 - (index * ListMemberGap));
        }
        else
        {
            index = m_LeftListItems.Count - 4;

            Vector3 pos = m_MemberScroll.transform.localPosition;
            pos.y = -2 + (index * ListMemberGap);
            m_MemberScroll.transform.localPosition = pos;

            UIPanel pn = m_MemberScroll.GetComponent("UIPanel") as UIPanel;
            pn.clipOffset = new Vector2(0, -30 - (index * ListMemberGap));
        }
    }


    void GoReadyMode()
    {


        m_SelectMember = null;

        m_SceneMode = SCENEMODE.ready;

        if (m_IsInit)
            m_ModeChangeAni.Play("Lobby_Save Fom");
        else
        {
            m_IsInit = true;
            m_ModeChangeAni.Play("Lobby_vs20 Intro");
        }



        ResetScrollView();
        SetSortMenuUI(m_SortKind);
    }

    void GoChangeMode()
    {
        m_SelectMember = null;

        m_SceneMode = SCENEMODE.change;
        m_ModeChangeAni.Play("Lobby_Change Fom");

        ResetScrollView();
        SetSortMenuUI(m_SortKind);

        SetFormation(true);
    }


    void SetFormation(bool isNeedLoad)  // 서버에서 받아온 정보 쓸껀지 말껀지
    {
        if (isNeedLoad)
        {
            m_MemberBattleArray.Clear();
            foreach (int t in UserData.Instance.userModel.memberBattleArray)
            {
                m_MemberBattleArray.Add(t);
            }
        }

        for (int i = 0; i < m_FormationList.Length; i++)
        {
            int memNo = m_MemberBattleArray[i + (m_FormationKind * Constants.FormationNum)];
            if (memNo != 0)
            {
                if (UserData.Instance.userModel.members_dic.ContainsKey(memNo.ToString()))
                    m_FormationList[i].SetMember(UserData.Instance.userModel.members_dic[memNo.ToString()], m_SortKind);
                else
                    m_FormationList[i].SetMember(null, m_SortKind);
            }
            else
                m_FormationList[i].SetMember(null, m_SortKind);
        }

        //foreach(Oc_MemberListItem_2 tOc in m_LeftListItems)
        //{
        //    tOc.SetListWithSortingKind(m_SortKind);
        //}

        RefreshFormationData();
    }

    public override void ButtonTouch(Collider collider)  // 버튼 터치 (터치 시작 끝 같은 오브젝트일때 터치 끝 시점에 호출)
    {
        Debug.Log(collider.name);

        if (collider.name.Contains("memberList_A"))
        {
            Oc_MemberListItem_2 Choise_ML = collider.GetComponent("Oc_MemberListItem_2") as Oc_MemberListItem_2;
            UIDragScrollView udsv = collider.GetComponent("UIDragScrollView") as UIDragScrollView;
            UIPanel scroll = udsv.scrollView.GetComponent("UIPanel") as UIPanel;

            //보이는 객체만 선택 가능
            bool isVisible = scroll.IsVisible(Choise_ML.m_LevelLabel) || scroll.IsVisible(Choise_ML.m_LevelLabel_On) ||
                scroll.IsVisible(Choise_ML.m_SbjectLabel) || scroll.IsVisible(Choise_ML.m_SbjectLabel_On);

            if (isVisible)
            {
                SetLeftListPos(Choise_ML);

                if (m_SceneMode == SCENEMODE.ready)
                {

                }
                else if (m_SceneMode == SCENEMODE.change)
                {
                    //if (m_SelectMember.no != Choise_ML.m_MemberModel.no)      // 이전 선택 길드원과 다를때
                    {
                        m_SelectMember = Choise_ML.m_MemberModel;

                        foreach (Oc_FormationItem tFi in m_FormationList)
                        {
                            if (tFi.m_Member != null)
                            {
                                if (tFi.m_Member.no == m_SelectMember.no)
                                {
                                    tFi.SetOnOff(true);
                                    // 선택 이펙트 추가
                                    m_SelectFx1.transform.localPosition = tFi.transform.localPosition;
                                    m_SelectFx1.particleSystem.Play();
                                    SoundController.PlaySound("UI_array_change");
                                }
                                else
                                {
                                    tFi.SetOnOff(false);
                                }
                            }
                        }
                    }
                }

                foreach (Oc_MemberListItem_2 t_ML in m_LeftListItems)
                {
                    if (t_ML.Equals(Choise_ML))
                        t_ML.SetOn(true);
                    else
                        t_ML.SetOff();
                }
            }
        }
        else if (collider.name.Contains("Button_Sort_"))
        {
            if (IsSortMenuOn)
            {
                string buttonName = collider.gameObject.name.Replace("Button_Sort_", "");
                int num = System.Convert.ToInt32(buttonName);
                SetSortMenuUI(num);
                m_SortAni.Play("sort_VS20_close");
            }
            else
            {
                for (int i = 0; i < SortingNum; i++)
                {
                    m_SortKindsLabel[i].text = TextController.GetStringWithId(tempString[i]);
                }

                m_SortAni.Play("sort_VS20_open");
            }
            IsSortMenuOn = !IsSortMenuOn;
        }
        else if (collider.name.Contains("Button_kind_Sort_"))
        {
            if (m_IsKindSortMenuOn)
            {
                string buttonName = collider.gameObject.name.Replace("Button_kind_Sort_", "");
                int num = System.Convert.ToInt32(buttonName);
                SetKindSortMenuUI(num);
                m_SortAni_Kind.Play("sort_close");
            }
            else
            {
                for (int i = 0; i < FormationMax; i++)
                {
                    m_KindSortKindsLabel[i].text = string.Format(TextController.GetStringWithId("forceFormationCombobox"), i + 1);  
                }

                m_SortAni_Kind.Play("sort_open");
            }
            m_IsKindSortMenuOn = !m_IsKindSortMenuOn;
        }
        else if (collider.name.Contains("Cell_Formation_"))
        {
            Oc_FormationItem fi = collider.GetComponent("Oc_FormationItem") as Oc_FormationItem;

            if (m_SelectMember != null)
            {
                foreach (Oc_FormationItem tFi in m_FormationList)
                {
                    tFi.SetOnOff(false);
                }

                if (fi.m_Member == null)
                {
                    bool isSelected = false;
                    Oc_FormationItem preFormation = null;
                    foreach (Oc_FormationItem tFi in m_FormationList)
                    {
                        if (tFi.m_Member != null)
                        {
                            if (tFi.m_Member.no == m_SelectMember.no)
                            {
                                preFormation = tFi;
                                isSelected = true;
                                break;
                            }
                        }
                    }

                    if (m_FormationMemberNum > MaxFormationMember - 1 && !isSelected)
                    {
                        //Popup_OneButton sc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
                        //sc.SetPopupWithTitleAndBody("알림", "");
                    }
                    else
                    {
                        if (preFormation != null)
                        {
                            SetFormationItem(preFormation, null);
                        }

                        SetFormationItem(fi, m_SelectMember, FXMode.first);
                    }

                }
                else if (fi.m_Member != m_SelectMember)
                {
                    MemberModel tMem = fi.m_Member;

                    foreach (Oc_FormationItem tFi in m_FormationList)
                    {
                        if (tFi.m_Member != null)
                        {
                            if (tFi.m_Member.no == m_SelectMember.no)
                            {
                                SetFormationItem(tFi, fi.m_Member, FXMode.second);
                                break;
                            }
                        }
                    }

                    SetFormationItem(fi, m_SelectMember, FXMode.first);
                }
                else
                {
                    SetFormationItem(fi, null);
                }

                RefreshFormationData();


                m_SelectMember = null;

                foreach (Oc_MemberListItem_2 t_ML in m_LeftListItems)
                {
                    t_ML.SetOff();
                }
            }
            else
            {
                if (fi.m_Member != null)
                {
                    m_SelectMember = fi.m_Member;

                    foreach (Oc_FormationItem tFi in m_FormationList)
                    {
                        if (tFi.m_Member != null)
                        {
                            tFi.SetOnOff(tFi.m_Member.no == m_SelectMember.no);
                        }
                    }

                    int itemListOnIndex = -1;
                    int index = 0;
                    foreach (Oc_MemberListItem_2 t_ML in m_LeftListItems)
                    {
                        if (t_ML.m_MemberModel.no == m_SelectMember.no)
                        {
                            t_ML.SetOn(true);
                            itemListOnIndex = index;
                        }
                        else
                            t_ML.SetOff();

                        index++;
                    }

                    if (itemListOnIndex != -1)
                        MoveScrollView(itemListOnIndex);
                }
            }
        }
        else
        {
            switch (collider.name)
            {
                case "Button_GoBattle":
                    {
                        if (m_IsCanBattle)
                        {
                            UserData.Instance.userModel.m_FormationPage = m_FormationKind;

                            for (int i = 0; i < Constants.FormationNum; i++)// in UserData.Instance.userModel.memberBattleArray)
                            {
                                if (UserData.Instance.userModel.m_3DmodelWithFormation[i] != null)
                                    UserData.Instance.userModel.m_3DmodelWithFormation[i].transform.parent = null;
                                DontDestroyOnLoad(UserData.Instance.userModel.m_3DmodelWithFormation[i]);
                            }
                            Debug.Log(UserData.Instance.userModel.id);
                            //SceneController.LoadLevel("Friend Battle");
                            //NetworkManager.Instance.C2S_START_RAIDBOSS_BATTLE(ResponseStartRaidBossBattle, 0);
                            NetworkManager.Instance.C2S_GSTAR_START_RAIDBOSS_BATTLE(WorldSceneManager_GStar.sentResearchAreaId, ResponseStartRaidBossBattle);

                            //SceneController.LoadLevel("Battle_Raid_Tiamats_01");
                            //SceneController.LoadLevel("Friend Battle");
                        }
                        else
                        {
                            Popup_OneButton sc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
                            sc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId("forceFormationGuide2"));
                        }
                    }
                    break;

                case "Button_updown":
                    {
                        m_IsDescending = !m_IsDescending;

                        collider.transform.Find("Up").gameObject.SetActive(!m_IsDescending);
                        collider.transform.Find("Down").gameObject.SetActive(m_IsDescending);

                        SetSortMenuUI(m_SortKind);
                    }
                    break;

                case "Button_Sort":
                    if (IsSortMenuOn)
                        m_SortAni.Play("sort_VS20_close");
                    else
                    {
                        for (int i = 0; i < SortingNum; i++)
                        {
                            m_SortKindsLabel[i].text = TextController.GetStringWithId(tempString[i]);
                        }

                        m_SortAni.Play("sort_VS20_open");
                    }

                    IsSortMenuOn = !IsSortMenuOn;
                    break;
                case "Button_kind_Sort":
                    if (m_IsKindSortMenuOn)
                        m_SortAni_Kind.Play("sort_close");
                    else
                    {
                        for (int i = 0; i < FormationMax; i++)
                        {
                            m_KindSortKindsLabel[i].text = string.Format(TextController.GetStringWithId("forceFormationCombobox"), i + 1);  
                        }
                        m_SortAni_Kind.Play("sort_open");
                    }

                    m_IsKindSortMenuOn = !m_IsKindSortMenuOn;
                    break;
                case "Button_Change Formation":
                    {
                        GoChangeMode();
                    }
                    break;
                case "Button_Save":
                    {
                        SaveAllFormaion();
                    }
                    break;
                case "Button_Cancle":
                    {
                        GoReadyMode();
                    }
                    break;
                case "Button_Auto":
                    {
                        AutoFormation();
                    }
                    break;
                case "Graph":
                    {
                        Popup_Lobby_vs20Detail sc = PopupManager.PushPopup(PopupKind.Lobby_vs20Detail) as Popup_Lobby_vs20Detail;
                        sc.SetPopupWithList(m_Skill_Att, m_Skill_Def, m_Max_Att, m_Max_Def);
                    }
                    break;
                case "Button_memberInfo":
                    {
                        Oc_MemberListItem_2 tOc = collider.transform.parent.parent.GetComponent("Oc_MemberListItem_2") as Oc_MemberListItem_2;

                        //if (m_SceneMode == SCENEMODE.ready)
                        {
                            Popup_Info_detail tPop = PopupManager.PushPopup(PopupKind.Info_detail) as Popup_Info_detail;
                            tPop.SetPopupWithMember(tOc.m_MemberModel);
                        }
                        //else
                        //{
                        //    foreach (Oc_FormationItem tFi in m_FormationList)
                        //    {
                        //        if (tFi.m_Member != null)
                        //        {
                        //            if (tFi.m_Member.no == tOc.m_MemberModel.no)
                        //            {
                        //                SetFormationItem(tFi, null);
                        //                break;
                        //            }
                        //        }
                        //    }

                        //    tOc.SetSelect(false);
                        //}
                    }
                    break;
                case "Button_Back":
                    BackButton();
                    break;
                case "Button_CancleSelect":
                    {
                        foreach (Oc_MemberListItem_2 t_ML in m_LeftListItems)
                        {
                            t_ML.SetOff();
                        }

                        if (m_SceneMode == SCENEMODE.change)
                        {
                            foreach (Oc_FormationItem tFi in m_FormationList)
                            {
                                tFi.SetOnOff(false);
                            }
                        }

                        m_SelectMember = null;
                    }
                    break;
            }
        }
    }

    enum FXMode
    {
        none,
        first,
        second
    }

    void SetFormationItem(Oc_FormationItem fi, MemberModel member, FXMode fxMode)
    {
        int no = 0;
        if (member != null)
            no = member.no;

        fi.SetMember(member, m_SortKind);
        m_MemberBattleArray[fi.index + (m_FormationKind * Constants.FormationNum)] = no;

        SoundController.PlaySound("UI_array_change");

        switch (fxMode)
        {
            case FXMode.first:
                m_SelectFx1.transform.localPosition = fi.transform.localPosition;
                m_SelectFx1.particleSystem.Play();
                break;
            case FXMode.second:
                m_SelectFx2.transform.localPosition = fi.transform.localPosition;
                m_SelectFx2.particleSystem.Play();
                break;
        }
    }

    void SetFormationItem(Oc_FormationItem fi, MemberModel member)
    {
        int no = 0;
        if (member != null)
            no = member.no;

        fi.SetMember(member, m_SortKind);
        m_MemberBattleArray[fi.index + (m_FormationKind * Constants.FormationNum)] = no;
    }


    void LeftListCollidersOn()
    {
        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            m_LeftListItems[i].collider.enabled = true;
        }
    }

    public override void BackButton()
    {
        if (m_SceneMode == SCENEMODE.ready)
        {
            foreach (GameObject gm in UserData.Instance.userModel.m_3DmodelWithFormation)
            {
                Destroy(gm);
            }

            {                
                UserData.Instance.raidBossId = 0;
                UserData.Instance.raidBossStartData = null;
                UserData.Instance.raidBossResultData = null;
                UserData.Instance.raidBossModel = null;

                UserData.Instance.researchResultData = null;
                UserData.Instance.expansionWarResultData = null;
                UserData.Instance.quickPvPResultData = null;
                UserData.Instance.quickPVPUserModel = null;

                WorldSceneManager.isSentSearch = WorldSceneManager.isSuccessSearch = false;
                WorldSceneManager.sentResearchAreaId = 0;

                if (StandbyScene.startMode == BattleStartMode.Research || StandbyScene.startMode == BattleStartMode.RaidBossFromResearch)
                    //SceneController.LoadLevel("World");
                    SceneController.LoadLevel("World_GStar");
                else
                    SceneController.LoadLevel("BossList");
            }
        }
        else if (m_SceneMode == SCENEMODE.change)
        {
            GoReadyMode();
        }
    }
    #endregion




    public override void UpdateScene()
    {

    }


    // 인포 패널에 보여지는 순서
    AptitudeID_New[] m_ShowOrder = new AptitudeID_New[5]
    {
        AptitudeID_New.melee,
        AptitudeID_New.range,
        AptitudeID_New.magic,
        AptitudeID_New.pulse,
        AptitudeID_New.special       
    };


    int[] m_Skill_Att = new int[SkillNum];
    int[] m_Skill_Def = new int[SkillNum];

    int m_Max_Att = 0;
    int m_Max_Def = 0;

    void RefreshFormationData()     // 포메이션 아이템에 세팅된 멤버 값으로 포메이션 데이터 처리 및 그래프 표현
    {
        List<MemberModel> selectedMem = new List<MemberModel>();

        for (int i = 0; i < SkillNum; i++)
        {
            m_Skill_Att[i] = 0;
            m_Skill_Def[i] = 0;
        }


        foreach (Oc_MemberListItem_2 tML in m_LeftListItems)
        {
            bool isSelect = false;

            if (tML.gameObject.activeSelf)
            {
                foreach (Oc_FormationItem tFI in m_FormationList)
                {
                    if (tFI.m_Member != null)
                    {
                        if (tML.m_MemberModel.no == tFI.m_Member.no)
                        {
                            isSelect = true;
                            selectedMem.Add(tFI.m_Member);
                            break;
                        }
                    }
                }
            }

            if (m_SceneMode == SCENEMODE.change)
                tML.SetSelect(isSelect);
            else
                tML.SetSelect(false);
        }

        m_FormationMemberNum = selectedMem.Count;

        foreach (MemberModel tMM in selectedMem)
        {
            m_Skill_Att[tMM.m_Stat.data.atkType - 1] += tMM.m_Stat.data.baseAtk;

            for (int i = 0; i < m_Skill_Def.Length; i++)
            {
                m_Skill_Def[i] += (short)tMM.m_Stat.data[m_ShowOrder[i]];
            }
        }

        // 그래프 업데이트
        // 스킬중 가장 큰값 찾기
        m_Max_Att = 0;
        m_Max_Def = 0;

        int Max_Att_Index = 0;
        int Max_Def_Index = 0;

        for (int i = 0; i < SkillNum; i++)
        {
            if (m_Max_Att < m_Skill_Att[i])
            {
                m_Max_Att = m_Skill_Att[i];
                Max_Att_Index = i;
            }

            if (m_Max_Def < m_Skill_Def[i])
            {
                m_Max_Def = m_Skill_Def[i];
                Max_Def_Index = i;
            }
        }

        for (int i = 0; i < SkillNum; i++)
        {
            if (m_Max_Att == 0)
            {
                m_Graph_Att_On[i].gameObject.SetActive(false);
                m_Graph_Att_Off[i].gameObject.SetActive(true);

                m_Graph_Att_Off[i].value = 0;
            }
            else
            {
                m_Graph_Att_On[i].gameObject.SetActive(m_Max_Att == m_Skill_Att[i] && m_Skill_Att[i] > 0);
                m_Graph_Att_Off[i].gameObject.SetActive(m_Max_Att != m_Skill_Att[i] && m_Skill_Att[i] > 0);

                m_Graph_Att_Value[i].text = m_Max_Att.ToString();

                float scale = 1.0f;
                Vector3 pos = m_Graph_Att_Value[i].transform.localScale;
                pos = pos * 1.5f;
                m_Graph_Att_Value[i].transform.localScale = pos;
                iTween.ScaleTo(m_Graph_Att_Value[i].gameObject, iTween.Hash("scale", new Vector3(-scale, scale, 1), "time", 0.3f));

                m_Graph_Att_On[i].value = m_Skill_Att[i] / (float)m_Max_Att;
                m_Graph_Att_Off[i].value = m_Skill_Att[i] / (float)m_Max_Att;
            }


            if (m_Max_Def == 0)
            {
                m_Graph_Def_On[i].gameObject.SetActive(false);
                m_Graph_Def_Off[i].gameObject.SetActive(true);


                m_Graph_Def_Off[i].value = 0;
            }
            else
            {
                m_Graph_Def_On[i].gameObject.SetActive(m_Max_Def == m_Skill_Def[i] && m_Max_Def > 0);
                m_Graph_Def_Off[i].gameObject.SetActive(m_Max_Def != m_Skill_Def[i] && m_Max_Def > 0);

                m_Graph_Def_Value[i].text = m_Max_Def.ToString();

                float scale = 1.0f;
                Vector3 pos = m_Graph_Def_Value[i].transform.localScale;
                pos = pos * 1.5f;
                m_Graph_Def_Value[i].transform.localScale = pos;
                iTween.ScaleTo(m_Graph_Def_Value[i].gameObject, iTween.Hash("scale", new Vector3(scale, scale, 1), "time", 0.3f));

                m_Graph_Def_On[i].value = m_Skill_Def[i] / (float)m_Max_Def;
                m_Graph_Def_Off[i].value = m_Skill_Def[i] / (float)m_Max_Def;
            }
        }
        

        if (selectedMem.Count > 0)
        {
            m_InfoOfFormaion.text = string.Format(TextController.GetStringWithId("forceFormationLabel4"),TextController.GetStringWithId( atkName[Max_Att_Index]), TextController.GetStringWithId(defName[Max_Def_Index]));
            m_IsCanBattle = true;
        }
        else
        {
            m_InfoOfFormaion.text = TextController.GetStringWithId("forceFormationGuide2");
            m_IsCanBattle = false;
        }


        if (m_SceneMode == SCENEMODE.ready)
        {

            for (int i = 0; i < m_3DModelPosition.Length; i++)
            {
                if (m_3DModelPosition[i].childCount > 0)
                {
                    DestroyImmediate(m_3DModelPosition[i].GetChild(0).gameObject);

                    //m_ColorPos[i].SetColor("_SpecColor", Color.white);
                }
            }

            GameObject tempObj = null;
            MemberModel tempModel = null;

            for (int i = 0; i < Constants.FormationNum; i++)// in UserData.Instance.userModel.memberBattleArray)
            {
                tempObj = null;

                int no = UserData.Instance.userModel.memberBattleArray[i + (m_FormationKind * Constants.FormationNum)];
                if (UserData.Instance.userModel.members_dic.ContainsKey(no.ToString()))
                {
                    tempModel = UserData.Instance.userModel.members_dic[no.ToString()];
                    tempObj = BattleResManager.CreateMassPawn(tempModel.model);
                    tempObj.name = UserData.Instance.userModel.members_dic[no.ToString()].no.ToString();
                    tempObj.transform.parent = m_3DModelPosition[i];
                    tempObj.transform.localScale = Vector3.one;
                    tempObj.transform.localPosition = Vector3.zero;
                    tempObj.transform.localRotation = Quaternion.Euler(Vector3.zero);
                    // MyUtil.UpdateLayer(tempObj.transform, LayerMask.NameToLayer("Pawn"));                    

                    var ani = tempObj.MakeComponent<Animation>();
                    ani.Play("idle01");

                    AttachWeapon(tempModel, tempObj);

                    //m_ColorPos[i].SetColor("_Color", Constants.CharInfoRareColor[tempModel.m_Stat.atkType]);
                }

                UserData.Instance.userModel.m_3DmodelWithFormation[i] = tempObj;
            }

            m_3DModelColorPosRoot.gameObject.SetActive(true);
        }
        else
        {
            for (int i = 0; i < m_3DModelPosition.Length; i++)
            {
                if (m_3DModelPosition[i].childCount > 0)
                {
                    DestroyImmediate(m_3DModelPosition[i].GetChild(0).gameObject);
                }
            }

            m_3DModelColorPosRoot.gameObject.SetActive(false);
        }
    }

    BattleCharInfo AttachWeapon(MemberModel member, GameObject _parent)
    {
        return AttachWeapon(_parent, member.leftItem, member.rightItem);
    }


    BattleCharInfo AttachWeapon(GameObject _parent, Item L_item, Item R_item)
    {
        int[] itemModelId = new int[2];

        if (R_item != null)
            itemModelId[0] = R_item.itemInfo.modelID;


        if (L_item != null)
            itemModelId[1] = L_item.itemInfo.modelID;

        BattleCharInfo charInfo = _parent.GetComponent("BattleCharInfo") as BattleCharInfo;

        BattleResManager.AttachWeaponLow(_parent, charInfo, itemModelId, true);

        MyUtil.UpdateLayer(_parent.transform, LayerMask.NameToLayer("Pawn"));

        return charInfo;
    }


    //더미 3개 포함 5개 로컬라이제이션 키값
    static string[] atkName = new string[5] { "combatAtkType1", "combatAtkType2", 
                    "combatAtkType3", "combatAtkType4", "combatAtkType5" };

    static string[] defName = new string[5] { "combatDefType1", "combatDefType2", 
                    "combatDefType3", "combatDefType4", "combatDefType5" };

    void SaveFormation()    // 포메이션 페이지 바꿀때 적용
    {
        //for (int i = 0; i < m_FormationList.Length; i++ )
        //{
        //    if(m_FormationList[i].m_Member != null)
        //    {
        //        m_MemberBattleArray[i + (m_FormationKind * Constants.FormationNum)] = m_FormationList[i].m_Member.no;
        //    }     
        //    else
        //    {
        //        m_MemberBattleArray[i + (m_FormationKind * Constants.FormationNum)] = 0;
        //    }
        //}      
    }

    void SaveAllFormaion()  // 서버에 올리기전 (수정완료 버튼에 적용)
    {
        int i = 0;
        foreach (int t in m_MemberBattleArray)
        {
            UserData.Instance.userModel.memberBattleArray[i] = t;
            i++;
        }

        int[] formation = new int[Constants.FormationNum * Constants.FormationKind];
        UserData.Instance.userModel.memberBattleArray.CopyTo(0, formation, 0, (Constants.FormationNum * Constants.FormationKind));

        NetworkManager.Instance.C2S_Apply_20BattleFormation(OnApply_20BattleFormationCallback, formation);
    }

    void OnApply_20BattleFormationCallback(ResponseModel<string> userData)
    {
        if (userData.ecode == 0)
        {
            GoReadyMode();
        }
    }

    void AutoFormation()
    {
        const int melee = 8;
        int index = 0;
        foreach (Oc_FormationItem tFi in m_FormationList)
        {
            SetFormationItem(tFi, null);
            //tFi.SetOnOff(false);
            index++;
        }

        List<MemberModel> members = new List<MemberModel>();

        // 근접줄 채우기
        index = 0;
        foreach (KeyValuePair<string, MemberModel> tMM in UserData.Instance.userModel.members_dic)
        {
            if (tMM.Value.m_Stat.atkType == 1) // 근접 타입
            {
                SetFormationItem(m_FormationList[index], tMM.Value);

                members.Add(tMM.Value);

                index++;

                if (index == melee)     // 근접 다채우면 브레이크
                    break;
            }
        }

        // 다음부터 랜덤 채우기
        foreach (KeyValuePair<string, MemberModel> tMM in UserData.Instance.userModel.members_dic)
        {
            if (index == 11)
            {
                index++;
                continue;
            }

            if (!members.Contains(tMM.Value))
            {
                SetFormationItem(m_FormationList[index], tMM.Value);

                index++;

                if (index > MaxFormationMember)     // 근접 다채우면 브레이크
                    break;
            }
        }

        RefreshFormationData();
    }

    private void ResponseStartRaidBossBattle(ResponseModel<RaidBossStartModel> result)
    {
        if (result.ecode != 0)
        {
            Popup_OneButton po = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
            po.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(string.Format("systemErrorText{0}", Mathf.Abs(result.ecode))));
            return;
        }
        StandbyScene.startMode = BattleStartMode.None;
        //		if( WorldSceneManager.isSentSearch )
        //		{
        //			WorldSceneManager.isSentSearch = WorldSceneManager.isSuccessSearch = false;
        //			WorldSceneManager.sentResearchAreaId = 0;
        //			UserData.Instance.researchResultData = null;
        //		}
        UserData.Instance.raidBossStartData = result.data;
        UserData.Instance.battleRandomSeed = result.data.seed;

        // 다대다전투 - 레이드 임시로 Battle_Raid_Tiamats_01만 사용.

        if( UserData.Instance.raidBossStartData.raidBossId == 10001 )
            SceneController.LoadLevel("Area_Boss_Sarpan_01");
        else if( UserData.Instance.raidBossStartData.raidBossId == 10002 )
            SceneController.LoadLevel("Area_Boss_Eltnen_01");
        else if (UserData.Instance.raidBossStartData.raidBossId == 10003)
            SceneController.LoadLevel("Area_Boss_Heiron_01");
        else if (UserData.Instance.raidBossStartData.raidBossId == 10004)
            SceneController.LoadLevel("Area_Boss_Ishalgen_01");

        //if( result.data.raidBossId == 10001 )
        //	SceneController.LoadLevel("Battle_Boss_Tiamats_01");
        //else
        //	SceneController.LoadLevel("Battle_Boss_Beshmundir_01");
    }

    public override void ShopButton()
    {
        foreach (GameObject gm in UserData.Instance.userModel.m_3DmodelWithFormation)
        {
            Destroy(gm);
        }
    }
}
